package com.demo.testversion1

import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import org.junit.Test
import java.io.BufferedReader
import java.io.FileReader

/**
 * Created by zhangyuncai on 2025/1/19.
 * 描述：
 */
class CoroutineTest03 {
    @Test
    fun `test release rosources`(): Unit = runBlocking {
        val job = launch {
            repeat(1000) { i ->
                println("sleeping:${i}")
                delay(500L)

            }
        }
        delay(1300)
        println("waiting")
        job.cancelAndJoin()
        println("quit")

    }

    @Test
    fun `test use function`(): Unit = runBlocking {
//        var bar = BufferedReader(FileReader("E:\\global_config.json"))
//        with(bar)
//        {
//            var line: String?
//            try {
//                while (true) {
//                    line = readLine() ?: break
//                    println(line)
//                }
//            } catch (e: Exception) {
//
//            } finally {
//
//                close()
//            }
//
//        }
        BufferedReader(FileReader("E:\\global_config.json")).use {
            var line: String?//use可以自动关闭文件对象
            while (true) {
                line = it.readLine() ?: break
                println(line)
            }
        }

    }

    @Test
    fun `test cancel with NonCancellable`(): Unit = runBlocking {
        val job = launch {
            try {
                repeat(1000) { i ->
                    println("sleeping:${i}")
                    delay(500L)

                }
            } catch (e: Exception) {

            } finally {
//                println("finally")
//                delay(1000L)
//                println("non-cancellable")
                withContext(NonCancellable) {//不会被取消
                    println("finally")
                    delay(1000L)
                    println("non-cancellable")
                }
            }

        }
        delay(1300)
        println("waiting")
        job.cancelAndJoin()
        println("quit")
    }
}